<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div class="dialog-content">
      <!-- 用户头像和输入区域 -->
      <div class="post-container">
        <div class="avatar-container">
          <img :src="userStore.avatar" class="avatar" alt="用户头像">
        </div>
        <div class="content-container">
          <!-- 富文本编辑区域 -->
          <div 
            ref="editorRef" 
            class="editor-content" 
            contenteditable="true" 
            @input="handleInput"
            placeholder="点击发表主题..."
            @focus="handleEditorFocus"
          ></div>
        </div>
      </div>
      
      <!-- 底部工具栏和发布按钮 -->
      <div class="footer-container">
        <div class="tools-container">
          <!-- 表情 -->
          <div class="tool-item">
            <EmojiPicker @select="onSelectEmoji" position="top">
              <img class="tool-icon" src="/public/icon/publish-topic/expression.svg" alt="表情">
            </EmojiPicker>
          </div>
          
          <!-- 图片 -->
          <div class="tool-item" @click="handleImageClick">
            <img class="tool-icon" src="/public/icon/publish-topic/image.svg" alt="图片">
          </div>
          
          <!-- 文件 -->
          <div class="tool-item" @click="handleFileClick">
            <img class="tool-icon" src="/public/icon/publish-topic/file.svg" alt="文件">
          </div>
          
          <!-- 加粗 -->
          <div class="tool-item" @click="handleBoldClick">
            <img class="tool-icon" src="/public/icon/publish-topic/bold.svg" alt="加粗">
          </div>
          
          <!-- 话题 -->
          <div class="tool-item tag-container">
            <div class="topic-trigger" @click="handleTopicClick">
              <img class="tool-icon" src="/public/icon/publish-topic/hashsign.svg" alt="话题">
            </div>
            <TagDropdown 
              :visible="showTagDropdown" 
              @select="onTagSelected" 
              @close="showTagDropdown = false"
              top="230%"
            />
          </div>
          
          <!-- 定时 -->
          <div class="tool-item" @click="handleScheduleClick">
            <img class="tool-icon" src="/public/icon/publish-topic/scheduled.svg" alt="定时">
          </div>
        </div>
        
        <div class="publish-container">
          <span class="count-text">({{ contentLength }}/10000)</span>
          <el-button type="primary" @click="handlePublish" :disabled="!canPublish">发布</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
  
  <!-- 分类选择弹窗 -->
  <CategoryDialog ref="categoryDialogRef" @confirm="onConfirmPublish" @close="onCancelPublish" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'
import EmojiPicker from '@/components/EmojiPicker/index.vue'
import TagDropdown from './TagDropdown.vue'
import CategoryDialog from './CategoryDialog.vue'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 弹窗状态
const dialogVisible = ref(false)
const title = ref('老强说')
const showTagDropdown = ref(false)

// 编辑器相关
const editorRef = ref<HTMLDivElement | null>(null)
const contentHTML = ref('')
const contentLength = ref(0)
const selectionRange = ref<Range | null>(null) // 保存选择范围

// 分类弹窗引用
const categoryDialogRef = ref<any>(null)

// 是否可以发布
const canPublish = computed(() => {
  return contentLength.value > 0
})

// 计算纯文本内容长度
const calculateContentLength = () => {
  if (!editorRef.value) return 0
  // 获取纯文本内容长度
  return editorRef.value.textContent?.length || 0
}

// 处理输入事件
const handleInput = () => {
  if (!editorRef.value) return
  contentHTML.value = editorRef.value.innerHTML
  contentLength.value = calculateContentLength()
  
  // 保存当前选择范围
  saveCurrentSelection()
}

// 保存当前选择范围
const saveCurrentSelection = () => {
  const selection = window.getSelection()
  if (selection && selection.rangeCount > 0) {
    selectionRange.value = selection.getRangeAt(0).cloneRange()
  }
}

// 恢复选择范围
const restoreSelection = () => {
  if (selectionRange.value && editorRef.value) {
    const selection = window.getSelection()
    if (selection) {
      selection.removeAllRanges()
      selection.addRange(selectionRange.value)
    }
  }
}

// 处理编辑器聚焦
const handleEditorFocus = () => {
  saveCurrentSelection()
}

// 打开弹窗
const openDialog = (options?: {
  activeTool?: string;
}) => {
  dialogVisible.value = true
  
  // 如果指定了要激活的工具，则触发对应工具
  if (options?.activeTool) {
    setTimeout(() => {
      activateTool(options.activeTool as string)
    }, 200)
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
  showTagDropdown.value = false
}

// 重置表单
const resetForm = () => {
  if (editorRef.value) {
    editorRef.value.innerHTML = ''
  }
  contentHTML.value = ''
  contentLength.value = 0
  selectionRange.value = null
}


// 处理标签选择
const onTagSelected = (tag: string) => {
  console.log('标签选中:', tag)
  
  // 获取当前选择
  if (!editorRef.value) return
  
  // 先聚焦编辑器
  editorRef.value.focus()
  
  // 恢复之前保存的选择范围
  restoreSelection()
  
  try {
    // 创建标签元素
    const tagElement = document.createElement('span')
    tagElement.className = 'topic-tag'
    tagElement.textContent = `#${tag}`
    
    // 获取当前选择范围
    const selection = window.getSelection()
    
    // 如果没有选择范围，创建一个新的范围
    if (!selection || selection.rangeCount === 0) {
      const range = document.createRange()
      range.selectNodeContents(editorRef.value)
      range.collapse(false) // 将范围折叠到末尾
      
      if (selection) {
        selection.removeAllRanges()
        selection.addRange(range)
      }
    }
    
    // 再次获取选择范围
    const range = selection?.getRangeAt(0)
    
    if (range) {
      // 插入标签
      range.deleteContents()
      range.insertNode(tagElement)
      
      // 添加空格
      const space = document.createTextNode(' ')
      range.setStartAfter(tagElement)
      range.setEndAfter(tagElement)
      range.insertNode(space)
      
      // 将光标移动到空格后面
      range.setStartAfter(space)
      range.setEndAfter(space)
      selection?.removeAllRanges()
      selection?.addRange(range)
      
      // 保存新的选择范围
      saveCurrentSelection()
    }
    
    // 更新内容
    handleInput()
  } catch (error) {
    console.error('插入标签出错:', error)
    
    // 备用方案：如果出错，直接在末尾添加标签
    if (editorRef.value) {
      const tagText = document.createTextNode(`#${tag} `)
      editorRef.value.appendChild(tagText)
      handleInput()
    }
  }
}

// 激活指定工具
const activateTool = (toolName: string) => {
  switch (toolName) {
    case 'emoji':
      // 聚焦编辑器，确保有正确的选择范围
      if (editorRef.value) {
        console.log('emoji')
        editorRef.value.focus()
        saveCurrentSelection()
        
        // 直接手动点击DOM中的表情按钮
        const emojiTrigger = document.querySelector('.emoji-trigger')
        if (emojiTrigger instanceof HTMLElement) {
          emojiTrigger.click()
        } else {
          console.error('找不到表情按钮元素')
        }
      }
      break
    case 'bold':
      if (editorRef.value) {
        editorRef.value.focus()
        saveCurrentSelection()
        execCommand('bold')
      }
      break
    case 'topic':
      // 聚焦编辑器，确保有正确的选择范围
      if (editorRef.value) {
        editorRef.value.focus()
        saveCurrentSelection()
        
        // 手动模拟点击话题按钮
        const topicTrigger = document.querySelector('.topic-trigger')
        if (topicTrigger instanceof HTMLElement) {
          topicTrigger.click()
        } else {
          // 如果找不到按钮，直接设置下拉菜单可见
          console.log('找不到话题按钮，直接展开下拉菜单')
          showTagDropdown.value = true
        }
      }
      break
    case 'image':
      ElMessage.info('上传图片功能待实现')
      break
    case 'file':
      ElMessage.info('上传文件功能待实现')
      break
    case 'schedule':
      ElMessage.info('定时发布功能待实现')
      break
  }
}

// 执行浏览器命令
const execCommand = (command: string, value: string = '') => {
  // 恢复选择范围
  restoreSelection()
  
  // 执行命令
  document.execCommand(command, false, value)
  
  // 聚焦编辑器
  editorRef.value?.focus()
  
  // 更新内容
  handleInput()
}

// 各种工具点击事件
const handleImageClick = () => {
  ElMessage.info('上传图片功能待实现')
}

const handleFileClick = () => {
  ElMessage.info('上传文件功能待实现')
}

const handleBoldClick = () => {
  execCommand('bold')
}

const handleTopicClick = (event: MouseEvent) => {
  // 阻止事件冒泡
  event.stopPropagation()
  
  // 先聚焦编辑器并保存选择范围
  if (editorRef.value) {
    editorRef.value.focus()
    saveCurrentSelection()
  }
  
  // 切换标签下拉菜单
  console.log('切换标签下拉菜单', !showTagDropdown.value)
  showTagDropdown.value = !showTagDropdown.value
}

const handleScheduleClick = () => {
  ElMessage.info('定时发布功能待实现')
}

// 选择表情
const onSelectEmoji = (emoji: any) => {
  if (!editorRef.value) return
  
  // 先聚焦编辑器
  editorRef.value.focus()
  
  // 恢复选择范围
  restoreSelection()
  
  // 获取当前选择
  const selection = window.getSelection()
  
  // 如果没有选择范围，创建一个新的范围
  if (!selection || selection.rangeCount === 0) {
    const range = document.createRange()
    range.selectNodeContents(editorRef.value)
    range.collapse(false) // 将范围折叠到末尾
    
    if (selection) {
      selection.removeAllRanges()
      selection.addRange(range)
    }
  }
  
  // 再次获取选择范围
  const range = selection?.getRangeAt(0)
  
  if (range) {
    // 在光标位置插入表情
    const textNode = document.createTextNode(emoji.i)
    range.deleteContents()
    range.insertNode(textNode)
    
    // 将光标移动到表情后面
    range.setStartAfter(textNode)
    range.setEndAfter(textNode)
    selection?.removeAllRanges()
    selection?.addRange(range)
    
    // 保存新的选择范围
    saveCurrentSelection()
    
    // 更新内容
    handleInput()
  }
}

// 发布帖子
const handlePublish = () => {
  if (!canPublish.value) {
    ElMessage.warning('请输入内容')
    return
  }
  
  // 准备发布数据
  const postData = {
    content: contentHTML.value,
    plainText: editorRef.value?.textContent || '',
    publishTime: new Date().toISOString()
  }
  
  // 打开分类选择弹窗
  if (categoryDialogRef.value) {
    categoryDialogRef.value.openDialog(postData)
  }
}

// 确认发布（选择分类后）
const onConfirmPublish = (finalPostData: any) => {
  console.log('最终发布数据:', finalPostData)
  
  // TODO: 调用发布API
  // 这里模拟API调用
  setTimeout(() => {
    ElMessage.success('发布成功')
    // 关闭弹窗
    handleClose()
  }, 1000)
}

// 取消发布
const onCancelPublish = () => {
  console.log('用户取消了发布')
  // 此处不需要其他操作，只记录日志
  // 分类弹窗已经关闭，不需要再关闭主发布弹窗
}

// 组件挂载后设置焦点
onMounted(() => {
  nextTick(() => {
    // 确保编辑器DOM元素已经渲染
    if (editorRef.value) {
      editorRef.value.focus()
      saveCurrentSelection()
    }
  })
})

// 暴露方法给外部使用
defineExpose({
  openDialog
})
</script>

<style scoped>
.dialog-content {
  padding: 0;
  position: relative;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn) {
  top: 1.25rem;
  right: 1.25rem;
}

:deep(.el-dialog__body) {
  padding: 0;
}

/* 帖子容器 */
.post-container {
  display: flex;
  padding: 1.25rem 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

/* 头像容器 */
.avatar-container {
  margin-right: 1rem;
}

.avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
}

/* 内容容器 */
.content-container {
  flex: 1;
}

/* 编辑器内容 */
.editor-content {
  min-height: 8rem;
  outline: none;
  font-size: 0.875rem;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
}

.editor-content:empty:before {
  content: attr(placeholder);
  color: #aaa;
}

/* 底部容器 */
.footer-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0 0;
}

/* 工具容器 */
.tools-container {
  display: flex;
  align-items: center;
}

/* 工具项 */
.tool-item {
  display: flex;
  align-items: center;
  margin-right: 1.5rem;
  cursor: pointer;
}

/* 标签容器 */
.tag-container {
  position: relative;
  /* display: inline-block; */
}
.topic-trigger{
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 工具图标 */
.tool-icon {
  width: 1.125rem;
  height: 1.125rem;
}

/* 发布容器 */
.publish-container {
  display: flex;
  align-items: center;
}

/* 字数统计 */
.count-text {
  color: #8b8e9d;
  font-size: 0.875rem;
  margin-right: 1rem;
}

/* 话题标签样式 */
:deep(.topic-tag) {
  color: #2563eb;
  font-weight: 500;
}
</style> 